package org.bambrikii.examples.rutext.lexer.custom;

import org.bambrikii.examples.rutext.lexer.ILexer;
import org.bambrikii.examples.rutext.lexer.custom.FractionPartLexer;
import org.bambrikii.examples.rutext.lexer.custom.IntegerPartLexer;
import org.bambrikii.examples.rutext.lexer.impl.LexerBase;
import org.bambrikii.examples.rutext.parser.IParser;
import org.bambrikii.examples.rutext.parser.ParserException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NumberLexer extends LexerBase<Double> {

	private static final Logger logger = LoggerFactory.getLogger(NumberLexer.class);

	public NumberLexer(IParser parser) {
		super(parser);
		addChild(new IntegerPartLexer(parser));
		addChild(new FractionPartLexer(parser));
	}

	@Override
	public Double lex() throws ParserException {
		Double result = new Double(0f);
		int n = 0;
		while (hasNext()) {
			int childenProcessed = 0;
			for (ILexer<?> child : getChildren()) {
				Object obj = child.lex();
				if (obj != null) {
					if (child instanceof IntegerPartLexer) {
						Double currentValue = (Double) obj;
						result = currentValue.doubleValue();
						n++;
					} else if (child instanceof FractionPartLexer) {
						Double currentValue = (Double) obj;
						result = result.doubleValue() + currentValue.doubleValue();
						n++;
					}
				}
				childenProcessed++;
			}
			if (getChildren().size() == childenProcessed) {
				logger.debug("skipping [" + getLast() + "]");
				break;
			}
		}
		if (n > 0) {
			return result;
		}
		return null;
	}
}
